import {
  Tree,
  Descriptions,
  Tag,
  message,
  Popconfirm,
  Input,
  Radio,
  Popover,
} from "antd";
import Layout from "../Shared/Layout";
import { useCallback, useEffect, useState } from "react";
import { request, requestDispatch } from "../../Api/api";
import { useDispatch } from "react-redux";
import MyButton from "../../Components/MyButton";
import { QuestionCircleOutlined } from "@ant-design/icons";
import AddRight from "../../Components/Operation/RightControl/AddRight";
const RightControl = () => {
  const [rightTrees, setRightTrees] = useState([]);
  const [currRight, setCurrRight] = useState({});
  const [addingRight, setAddingRight] = useState({});
  const [isUpdating, setIsUpdating] = useState(false);
  const [updatingRight, setUpdatingRight] = useState({});
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [open, setOpen] = useState(false);
  const dispatch = useDispatch();
  const items = [
    {
      label: "名称",
      children: !isUpdating ? (
        currRight.name
      ) : (
        <Input
          value={updatingRight.name}
          onChange={(e) =>
            setUpdatingRight({ ...updatingRight, name: e.target.value })
          }
        />
      ),
    },
    {
      label: "请求方法",
      children: !isUpdating ? (
        currRight.requestMethod
      ) : (
        <Input
          value={updatingRight.requestMethod}
          onChange={(e) =>
            setUpdatingRight({
              ...updatingRight,
              requestMethod: e.target.value,
            })
          }
        />
      ),
    },
    {
      label: (
        <>
          管控的地址&nbsp;&nbsp;
          <Popover
            content={
              <>
                <p>
                  地址分为两部分，一部分是前端页面的地址，另一部分是Api接口的地址。
                </p>
                <p>
                  例如："/home","/login"，是前端页面的地址，"api/login/login","api/right/list"是Api接口的地址。
                </p>
              </>
            }
            title="说明"
          >
            <QuestionCircleOutlined style={{ cursor: "pointer" }} />
          </Popover>
        </>
      ),
      children: !isUpdating ? (
        currRight.url
      ) : (
        <Input
          value={updatingRight.url}
          onChange={(e) =>
            setUpdatingRight({ ...updatingRight, url: e.target.value })
          }
        />
      ),
    },
    {
      label: (
        <>
          序号&nbsp;&nbsp;
          <Popover
            content={
              <>
                <p>序号用于排序，数字越小，排在越前面。</p>
                <p>
                  例如：系统管理的权限，序号为1，其他权限的序号为2，以此类推。
                </p>
                <p>
                  序号始终从1开始，修改序号或新增序号将会导致序号重排（删除不会）。
                </p>
                <p>这也就导致了在合理的范围内（譬如排序连续没有零和负数）,</p>
                <p>序号是几就会排在第几位。</p>
              </>
            }
            title="说明"
          >
            <QuestionCircleOutlined style={{ cursor: "pointer" }} />
          </Popover>
        </>
      ),
      children: !isUpdating ? (
        currRight.no
      ) : (
        <Input
          value={updatingRight.no}
          onChange={(e) =>
            setUpdatingRight({ ...updatingRight, no: e.target.value })
          }
        />
      ),
    },
    {
      label: "是否发布",
      children: !isUpdating ? (
        currRight.isPublish ? (
          <Tag color="green">已发布</Tag>
        ) : (
          <Tag color="red">未发布</Tag>
        )
      ) : (
        <Radio.Group
          value={updatingRight.isPublish === 1 ? true : false}
          onChange={(e) =>
            setUpdatingRight({
              ...updatingRight,
              isPublish: e.target.value ? 1 : 0,
            })
          }
        >
          <Radio value={true}>是</Radio>
          <Radio value={false}>否</Radio>
        </Radio.Group>
      ),
    },
    {
      label: "是否禁用",
      children: !isUpdating ? (
        currRight.isBan ? (
          <Tag color="red">已禁用</Tag>
        ) : (
          <Tag color="green">未禁用</Tag>
        )
      ) : (
        <Radio.Group
          value={updatingRight.isBan === 1 ? true : false}
          onChange={(e) =>
            setUpdatingRight({
              ...updatingRight,
              isBan: e.target.value ? 1 : 0,
            })
          }
        >
          <Radio value={true}>是</Radio>
          <Radio value={false}>否</Radio>
        </Radio.Group>
      ),
    },
  ];
  const getAllKeys = useCallback((trees) => {
    let keys = [];
    function loop(trees) {
      trees.forEach((item) => {
        keys.push(item.id);
        if (item.children) {
          loop(item.children);
        }
      });
    }
    loop(trees);
    return keys;
  }, []);
  const bind = useCallback(async () => {
    let res = await request("/right/tree", {}, "GET");
    if (res.code >= 0) {
      setRightTrees(res.data);
      setExpandedKeys(getAllKeys(res.data));
      setCurrRight(res.data[0]);
    }
  }, [getAllKeys]);
  const justBind = async () => {
    let res = await request("/right/tree", {}, "GET");
    if (res.code >= 0) {
      setRightTrees(res.data);
    }
  };
  useEffect(() => {
    async function fetchData() {
      bind();
    }
    fetchData();
  }, [dispatch, bind]);
  // 切换权限
  const handleChangeRight = (keys, e) => {
    if (e.selected) {
      setCurrRight(e.node);
    }
  };
  // 实际的操作 begin
  // 新增子级
  const addChild = async (data) => {
    let res = await requestDispatch(dispatch, "/right/add", data, "POST");
    if (res.code >= 0) {
      message.success(res.message);
      justBind();
      setCurrRight(res.data);
      setOpen(false);
    } else {
      message.error(res.message);
    }
  };
  // 编辑权限
  const editRight = async () => {
    if (isUpdating) {
      let res = await requestDispatch(
        dispatch,
        `/right/update`,
        { ...updatingRight },
        "POST"
      );
      if (res.code >= 0) {
        toggleUpdate();
        message.success(res.message);
        justBind();
        setCurrRight(res.data);
      } else {
        message.error(res.message);
      }
    }
  };
  // 删除权限
  const deleteRight = async (id) => {
    let res = await requestDispatch(
      dispatch,
      `/right/delete`,
      { id: id },
      "POST"
    );
    if (res.code >= 0) {
      message.success(res.message);
      bind();
    } else {
      message.error(res.message);
    }
  };
  // 实际的操作 end
  //展示新增子级弹窗
  const showAddModal = () => {
    setAddingRight({ parentId: currRight.id });
    setOpen(true);
  };
  // 切换编辑状态
  const toggleUpdate = () => {
    if (!isUpdating) {
      setUpdatingRight({ ...currRight });
    } else {
      setUpdatingRight({});
    }
    setIsUpdating(!isUpdating);
  };
  return (
    <Layout>
      <AddRight
        right={addingRight}
        open={open}
        onCancel={() => {
          setOpen(false);
        }}
        onOk={addChild}
      ></AddRight>
      <div className="container">
        <div className="container-left">
          <Tree
            blockNode
            onSelect={handleChangeRight}
            treeData={rightTrees}
            expandedKeys={expandedKeys}
            onExpand={setExpandedKeys}
            selectedKeys={[currRight.id]}
            fieldNames={{ title: "name", key: "id", children: "children" }}
          />
        </div>
        <div className="container-right">
          <Descriptions
            layout="vertical"
            bordered
            items={items}
            title="权限信息"
            extra={
              isUpdating ? (
                <div className="extra">
                  <div
                    className="extra-btn"
                    onClick={() => setIsUpdating(false)}
                  >
                    <MyButton>{"取消"}</MyButton>
                  </div>
                  <div className="extra-btn" onClick={editRight}>
                    <MyButton type={"primary"}>{"保存"}</MyButton>
                  </div>
                </div>
              ) : (
                <div className="extra">
                  <Popconfirm
                    title="删除权限"
                    description="您确定要删除该权限吗?"
                    onConfirm={() => deleteRight(currRight.id)}
                    okText="确认"
                    cancelText="取消"
                  >
                    <div className="extra-btn">
                      <MyButton type="danger">删除</MyButton>
                    </div>
                  </Popconfirm>
                  <div className="extra-btn" onClick={showAddModal}>
                    <MyButton type="success">新增子级</MyButton>
                  </div>
                  <div className="extra-btn" onClick={toggleUpdate}>
                    <MyButton type={"warning"}>编辑</MyButton>
                  </div>
                </div>
              )
            }
          ></Descriptions>
        </div>
      </div>
    </Layout>
  );
};

export default RightControl;
